package main

import (
	"context"
	"embed"
	"errors"
	"fmt"
	"lightshare/modules"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

//go:embed assets/*
var assets embed.FS

func main() {
	var config modules.Config = modules.DoInit(assets)

	// 添加favicon.ico处理
	http.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {
		http.NotFound(w, r)
	})
	http.HandleFunc("/list_directories", modules.ListDirectories)
	http.HandleFunc("/download/", modules.DownloadFile)
	http.HandleFunc("/upload", modules.UploadFile)
	http.HandleFunc("/upload_from_url", modules.UploadFromURL)
	http.HandleFunc("/get_file_info", modules.GetFileInfoFromURL)
	http.HandleFunc("/search/", modules.SearchFiles)
	http.HandleFunc("/cli", modules.HandleCli)
	http.HandleFunc("/cli/", modules.HandleCli)
	http.HandleFunc("/cli/search", modules.CliSearch)
	http.HandleFunc("/cli/search/", modules.CliSearch)
	http.HandleFunc("/cli/list", modules.CliList)
	http.HandleFunc("/cli/list/", modules.CliList)
	http.HandleFunc("/assets/", modules.ServeStatic)
	http.HandleFunc("/check_upload_status", modules.CheckUploadStatus)
	http.HandleFunc("/upload_chunk", modules.UploadChunk)
	http.HandleFunc("/merge_chunks", modules.MergeChunks)

	http.HandleFunc("/temp/upload", modules.TempUploadHandler)
	http.HandleFunc("/temp/upload_from_url", modules.TempUploadFromURL)
	http.HandleFunc("/temp/get/", modules.TempGetHandler)
	http.HandleFunc("/temp/download/", modules.TempDownloadHandler)

	http.HandleFunc("/", modules.ShowIndex)

	address := fmt.Sprintf("%s:%d", config.Server.Host, config.Server.Port)
	log.Printf("监听地址: %s", address)

	// 检查端口是否被占用
	if modules.IsPortInUse(config.Server.Port) {
		log.Fatalf("启动失败：端口 %d 已被占用", config.Server.Port)
	}

	// 创建可优雅关闭的HTTP服务器
	server := &http.Server{
		Addr:    address,
		Handler: nil,
	}

	// 创建信号通道
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt, syscall.SIGTERM)

	// 在goroutine中启动服务器
	go func() {
		if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Fatalf("服务器启动失败: %v", err)
		}
	}()

	// 等待中断信号
	<-quit
	log.Println("接收到停止信号，正在关闭服务器...")

	// 创建5秒超时的上下文
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	// 优雅关闭服务器
	if err := server.Shutdown(ctx); err != nil {
		log.Printf("服务器关闭错误: %v", err)
	}

	log.Println("服务器已停止")
}
